<template>
  <div class="banner">
    <div class="imgbox" :style="{left:pos}">
      <div class="item" v-for="(item,idx) in msg" :key="idx">
        <p>{{item.title}}</p>
      </div>
    </div>
    <div class="btns">
      <input type="button" class="left" value="<" @click="left">
      <input type="button" class="right" value=">" @click="right">
    </div>
  </div>
</template>

<script>
import {ref} from "vue";
export default {
  name: 'Banner',
  props: {
    msg: Array,
    index: {
      type:Number,
      default: 0
    }
  },
  setup(props, context){
    const index = ref(props.index);
    const pos = ref("0px");

    const left = ()=>{
      if(index.value === 0){
        index.value = props.msg.length-1;
      }else{
        index.value--;
      }
      move();
    }
    const right = ()=>{
      if(index.value === props.msg.length-1){
        index.value = 0;
      }else{
        index.value++;
      }
      move();
    }

    const move = ()=>{
      pos.value = -index.value * 300 + "px";

      context.emit("getIndex", index.value);
    }

    move();
    
    return {
      left, right, pos
    }
  }
}
</script>

<style scoped>
.banner{width:300px;margin:0 auto;position:relative;}
.banner .imgbox{width:1200px;height:200px;position: absolute;left:0;}
.imgbox .item{width:300px;font-size:100px;text-align:center;height:200px;line-height:200px;float:left}
.imgbox .item p{margin:0;}
.imgbox .item:nth-child(1){background:red}
.imgbox .item:nth-child(2){background:green}
.imgbox .item:nth-child(3){background:blue}
.imgbox .item:nth-child(4){background:yellow}
.btns{position:absolute; top:200px;}
</style>
